package com.wjm.machine.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.wjm.entity.Record;
import com.wjm.entity.StuRecInfo;
import com.wjm.entity.Student;
import com.wjm.service.impl.RecordServiceImpl;
import com.wjm.service.impl.StudentServiceImpl;
import com.wjm.util.CacheUtil;
import com.wjm.util.JsonUtil;
import com.wjm.util.StringUtil;

@Controller
@RequestMapping("/machine/client")
@SessionAttributes("student")
public class MachineController {

	@Resource(name = "studentService")
	private StudentServiceImpl studentService;
	@Resource(name = "recordService")
	private RecordServiceImpl recordService;

	@RequestMapping("/sure")
	@ResponseBody
	public String sureRec(String stuNo, String stuPass, Model model) {
		String result = "";
		try {
			Record record = null;
			for (Map.Entry<Integer, Record> entry : CacheUtil.getRecords().entrySet()) {
				record = entry.getValue();
				if (record != null && record.getStuNo().equals(stuNo)) {
					// 如果是入座状态直接返回
					if (record.getRecStatus() == 2) {
						return "{\"result\":\"sure_fail\"}";
					}
					record.setRecStatus(2);
					if (recordService.update(record)) {
						Map<String, Object> map = new HashMap<>();
						map.put("result", "sure_success");
						map.put("rec", record);
						result = JsonUtil.getJson(map);
					} else {
						record.setRecStatus(1);
						result = "{\"result\":\"sure_fail\"}";
					}
					return result;
				}
			}
			// 如果没有直接返回，那么表明没有预约
			Student stu = studentService.login(stuNo, stuPass);
			// 由于是刷卡，所以肯定能登陆
			if (stu != null) {
				model.addAttribute(StringUtil.STUDENT_KEY, stu);
			}
			result = "{\"result\":\"no_rec\"}";
		} catch (Exception e) {
			e.printStackTrace();
			result = "{\"result\":\"error\"}";
		}
		return result;
	}

	@RequestMapping("/leave")
	@ResponseBody
	public String leave(String stuNo, String stuPass, Model model) {
		String result = "";
		try {
			Record record = null;
			for (Map.Entry<Integer, Record> entry : CacheUtil.getRecords().entrySet()) {
				record = entry.getValue();
				if (record != null && record.getStuNo().equals(stuNo)) {

					// 如果是已经离开状态，那么直接返回
					if (record.getRecStatus() == 1) {
						return "{\"result\":\"sure_fail\"}";
					}

					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String date = record.getRecDate();
					record.setRecDate(sdf.format(new Date()));
					record.setRecStatus(1);
					if (recordService.update(record)) {
						result = "{\"result\":\"leave_success\"}";
					} else {
						record.setRecDate(date);
						record.setRecStatus(2);
						result = "{\"result\":\"leave_fail\"}";
					}
					return result;
				}
			}
			// 如果遍历完后都没有返回，那么说明没有预约，则登陆
			Student stu = studentService.login(stuNo, stuPass);
			// 由于是刷卡，所以肯定能登陆
			if (stu != null) {
				model.addAttribute(StringUtil.STUDENT_KEY, stu);
			}
			result = "{\"result\":\"no_rec\"}";
		} catch (Exception e) {
			e.printStackTrace();
			result = "{\"result\":\"error\"}";
		}
		return result;
	}

	public String complete(String stuNo, String stuPass) {
		String result = "";
		try {
			Record record = null;
			int deskId = 0;
			for (Map.Entry<Integer, Record> entry : CacheUtil.getRecords().entrySet()) {
				record = entry.getValue();
				if (record != null && record.getStuNo().equals(stuNo)) {
					deskId = record.getDeskId();
					int status = record.getRecStatus();
					record.setRecStatus(2);
					if (status != 2) {
						recordService.update(record);
					}
					result = "{\"result\":\"complete_success\"}";
					break;
				}
				record = null;
			}
			if (record != null && deskId > 0) {
				CacheUtil.getRecords().remove(deskId);
			} else {
				result = "{\"result\":\"complete_fail\"}";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/cancel")
	@ResponseBody
	public String cancel(String stuNo, String stuPass) {
		String result = "";
		try {
			Record record = null;
			int deskId = 0;
			for (Map.Entry<Integer, Record> entry : CacheUtil.getRecords().entrySet()) {
				record = entry.getValue();
				if (record != null && record.getStuNo().equals(stuNo)) {
					// 记录座位id，移除预约信息时用到
					deskId = record.getDeskId();
					int status = record.getRecStatus();
					record.setRecStatus(3);
					if (recordService.update(record)) {
						// 取消完成，更新当天预约信息
						StuRecInfo info = CacheUtil.getStuRecInfos().get(stuNo);
						if (info != null) {
							info.setCancel(info.getCancel() + 1);
							info.setIsHave(false);
						}
						result = "{\"result\":\"cancel_success\"}";
					} else {
						record.setRecStatus(status);
						result = "{\"result\":\"cancel_fail\"}";
					}
					break;
				} else {
					result = "{\"result\":\"cancel_fail\"}";
				}
			}
			if (record != null && deskId > 0) {
				CacheUtil.getRecords().remove(deskId);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = "{\"result\":\"error\"}";
		}
		return result;
	}

	@RequestMapping("/logout")
	public String logout(Model model) {
		String result = "redirect:/machine/client";
		model.addAttribute(StringUtil.STUDENT_KEY, null);
		return result;
	}

	@RequestMapping("")
	public String machine(String res) {
		if (res == null || res.equals("")) {
			res = "index";
		}
		String result = "/machine/" + res;
		return result;
	}
}
